package com.leetao.wxmsg.common.utils;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author 菅江晖
 * @date 2021/3/8 - 11:18
 */
public class HttpUtils {
    /**
     * 内容类型标签
     */
    public static final String CONTENT_TYPE_TAG = "content-type";

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * http 请求
     *
     * @param requestUrl 请求地址
     * @param requestMethod 请求方法
     * @param outputStr 请求参数
     * @param contentType 请求内容类型
     * @return 结果 or null
     */
    public static String httpRequest(String requestUrl, String requestMethod, String outputStr,String contentType) {
        log.info("【微信消息订阅服务器】 【发送HTTP请求】 请求方法:[{}], 地址:[{}], 请求头[content-type:{}], 请求体: {}",requestMethod,requestUrl,contentType,outputStr);
        // 创建SSLContext
        StringBuffer buffer = null;
        try {
            //请求地址
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方法
            conn.setRequestMethod(requestMethod);
            //请求头
            conn.setRequestProperty(CONTENT_TYPE_TAG,contentType);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();

            // 往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes(StandardCharsets.UTF_8));
                os.close();
            }

            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            br.close();

        } catch (Exception e) {
            log.error("【微信消息订阅服务器】 [HTTP ERROR] :{}",e.getMessage());
        }

        String result = buffer != null ? buffer.toString() : null;
        log.info("【微信消息订阅服务器】 【收到HTTP响应】 响应内容: {}",result);
        return result;
    }
}
